package com.byd.dms.serialize;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.byd.dms.entity.Dept;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class MapToListDeserializer implements ObjectDeserializer {
    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        System.out.println("fieldName = " + fieldName);
        System.out.println("type = " + type);
        System.out.println("type.getTypeName() = " + type.getTypeName());
        
        // https://www.jianshu.com/p/ee2ce1daf49d
        JSONLexer lexer = parser.getLexer();
        String val = lexer.stringVal();
        System.out.println("val = " + val);
        
        Object parse = parser.parse(fieldName);
        String text = parse.toString();
        
        System.out.println("parse  = " + parse);
        System.out.println("parseClass  = " + parse.getClass().getName());
        System.out.println(type instanceof LinkedList);
        Class<? extends Type> aClass = type.getClass();
        
        if (type instanceof LinkedList) {
            System.out.println(" =ddddddddddddddddddd");
        }
        System.out.println("text = " + text);
        
        //Object o1 = JSONObject.parseObject(text, type);
        //Object o2 = JSONObject.parseObject(text, new TypeReference(aClass) {
        //});
        
        
        Map<Integer, Dept> integerDeptHashMap = JSON.parseObject(text,
                new TypeReference<HashMap<Integer, Dept>>() {
                });
        
        System.out.println("integerDeptHashMap = " + integerDeptHashMap);
        
        if (integerDeptHashMap != null) {
            return (T) new LinkedList<>(integerDeptHashMap.values());
        }
        
        
        //Map<Integer,Dept> map = jsonObject;
        //System.out.println("map = " + map);
        
        List<Dept> depts = new LinkedList<>();
        depts.add(new Dept(12L, "自定义部门", 33));
        
        return (T) depts;
    }
    
    @Override
    public int getFastMatchToken() {
        return 0;
    }
}
